package servidorVehiculo.DAO;

import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Random;


public class FotoDAO {

	private static FotoDAO instance;
	private Connection connection;
	
	public static void init() throws SQLException{
		instance = new FotoDAO();
		instance.connection = DAOServidorVehiculo.getConnection();
	}
	
	public static void close(){
		instance = null;
	}
	
	
	public static String getFoto() throws FileNotFoundException, SQLException{
		return instance.getPhoto();
	}
	
	private String getPhoto() throws SQLException, FileNotFoundException{
		PreparedStatement smt = connection.prepareStatement("SELECT COUNT(*) FROM FOTO");
		ResultSet rs = smt.executeQuery();
		rs.next();
		int max = rs.getInt(1);
		if(max > 0){
			int id = new Random().nextInt(max);
			smt = connection.prepareStatement("SELECT RUTA FROM FOTO WHERE ID = ?");
			smt.setInt(1, id);
			rs = smt.executeQuery();
			rs.next();
			return rs.getString(1);
		} else {
			return null;
		}
	}

}
